package com.wangsh.splider.common.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 线程池的工具类
 * @author wangshMac
 *
 */
public class ExecutorServiceUtil
{
	/* 创建一个缓存的线程池
	 * 线程池启动以后不用关闭
	 *  */
	private static ExecutorService exeSvc = Executors.newCachedThreadPool();
	
	/**
	 * 提交,主线程不用等待
	 */
	public static List<Object> submit(List<Callable<Object>> callList)
	{
		List<Object> resultList = new ArrayList<Object>();
		for (Iterator iterator = callList.iterator(); iterator.hasNext();)
		{
			Callable<Object> call = (Callable<Object>) iterator.next();
			Object resTemp = exeSvc.submit(call);
			resultList.add(resTemp);
		}
		return resultList ; 
	}
	
	/**
	 * 提交,主线程不用等待
	 */
	public static Object submit(Callable<Object> call)
	{
		return exeSvc.submit(call);
	}
	
	/**
	 * 主线程得等待
	 * @throws InterruptedException 
	 */
	public static List<Future<Object>> invokeAll(List<Callable<Object>> callList) throws InterruptedException
	{
		if(callList.size() > 0 )
		{
			return exeSvc.invokeAll(callList);
		}
		return Collections.emptyList();
	}
	
	/**
	 * 关闭线程池服务
	 */
	public static void shutdown()
	{
		exeSvc.shutdown();
		/* 一旦抛异常,重新开启一个新的线程池 */
		exeSvc =Executors.newCachedThreadPool();
	}
}
